<?php
namespace app\manage\controller;

use app\manage\controller\BaseController;
use app\manage\model\ArticleImg;
use think\facade\Db;
use think\facade\View;
use app\manage\model\Cate as Catemodel;
use app\manage\model\Article as Articlemodel;

class Article extends BaseController
{
    public function index()
    {
        $data=input('get.');
        //获取参数 返回首页
        if (!isset($data['cate'])) {
            $data['cate']=0;
        }
        if (!isset($data['key'])) {
            $data['key']='';
        }
        View::assign('data', $data);
        //搜索 key
        if ($data['cate']==0) {
            $map=true;
        } elseif ($ar=Catemodel::where('fid', $data['cate'])->column('id')) {
            $map=['a.cateid'=>$ar];
        } else {
            $map=['a.cateid'=>$data['cate']];
        }
            
        $info=Articlemodel::alias('a')
            ->join('cate c', 'a.cateid = c.id', 'LEFT')
            ->field('a.*,c.catename')
            ->where($map)->where('a.title', 'like', '%'.$data['key'].'%')
            ->order('a.id desc')
            ->paginate(10, false, ['query'=>request()->param()])->each(function ($item, $key) {
                if ($w=ArticleImg::where('aid', $item['id'])->value('pic')) {
                    $item['pic'] = $w;
                }
                return $item;
            });
        View::assign('info', $info);
        View::assign('count1', $info->total());
        $cate=new Catemodel();
        $datasort=$cate->tree();
        foreach ($datasort as $k=>$v) {
            if ($v['type']==2) {
                unset($datasort[$k]);
            }
        }
        View::assign('datasort', $datasort);
        return View::fetch();
    }
    public function ajax()
    {
        $data=input('post.');
        //抓取  新闻
        if ($data['type'] == 'article_zhua') {
            $info = $this->curl('http://v.juhe.cn/toutiao/index?type=top&key=5433111e9bf3a6c1b3d0483ce37a676f&is_filter=1&page_size=' . $data['num'] . '&page=' . mt_rand(1, 10));
            if ($info["reason"] == "success") {
                foreach ($info["result"]["data"] as $v) {
                    $con = $this->curl('http://v.juhe.cn/toutiao/content?key=5433111e9bf3a6c1b3d0483ce37a676f&uniquekey=' . $v['uniquekey']);
                    if (isset($con["result"]["detail"])) {
                        $in = $con["result"]["detail"];
                        $content = $con["result"]["content"];
                        $a = [
                            'title' => $in['title'],
                            'desc' => mb_substr(preg_replace('/\&nbsp;/', '', strip_tags($content)), 0, 200),
                            'pic' => $in["thumbnail_pic_s"],
                            'text' => $content,
                            'time' => strtotime($in['date']),
                            'cateid' => $data['cate_id'],
                            'faid' => 0,
                            'click_wai' => mt_rand(500, 2000),
                            'url' => $in['url'],
                            'laiyuan' => ''
                        ];
                        Articlemodel::create($a);
                    }
                }
                return json(['code' => 1, 'msg' => '抓取成功']);
            } else {
                return json(['code' => 0, 'msg' => $info["reason"]]);
            }
        }
        if ($data['type']=='article_del') {
            if (Articlemodel::destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='article_all') {
            if (Articlemodel::destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='cate_article') {
            $res=\app\manage\model\Cate::where('id', $data['id'])->value('type');
            if ($res) {
                return json(['code'=>$res]);
            } else {
                return json(['code'=>0]);
            }
        }
        if ($data['type']=='article_del_img') {
            if (ArticleImg::destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='article_start') {
            if (Articlemodel::where('id', $data['id'])->update(['isopen'=>1])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='article_stop') {
            if (Articlemodel::where('id', $data['id'])->update(['isopen'=> 0])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='diqu_change_shi') {
            $res=Db::name('area')->where('fid', input('id'))->select();
            if ($res) {
                return json(['code'=>1,'data'=>$res]);
            } else {
                return json(['code'=>0]);
            }
        }
        if ($data['type']=='diqu_change_xian') {
            $res=Db::name('area')->where('fid', input('id'))->select();
            if ($res) {
                return json(['code'=>1,'data'=>$res]);
            } else {
                return json(['code'=>0]);
            }
        }

        return json(['code'=>0]);
    }
    public function add()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $validate = new \app\manage\validate\Article;
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            $config=Db::name('config')->column('value', 'key');
            $file = request()->file('');
            if (isset($file['pic'])) {
                try {
                    validate(['pic'=>'fileSize:5242880|fileExt:jpg,png,gif,webp,jpeg'])->check($file);
                    $info=\think\facade\Filesystem::disk('public')->putFile( 'article', $file['pic']);
                    $data['pic']='/storage/'.strtr($info, " \ ", " / ");
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
            } else {
                if (isset($data['ti'])) {

                    preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);

                    //压缩图片
                    if($config["is_ya"] ==1){
                        foreach ($arr[1] as $k=>$v) {
                            if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
                                $newarr=getimagesize(substr($v, 1));
                                if ($newarr[0] >$config["ya_w"]) {
                                    $image = \think\Image::open(substr($v, 1));
                                    $h=$config["ya_w"]*$newarr[1]/$newarr[0];
                                    $image->thumb($config['ya_w'], $h)->save(substr($v, 1));
                                }
                            }
                        }
                    }
                    //提取第一张图片
                    foreach ($arr[1] as $k=>$v) {
                        if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
                            $newarr=getimagesize(substr($v, 1));
                            if ($newarr[0] >100 and $newarr[1] >100) {
                                //图片转移位置
                                if (!is_dir("storage/article/".date("Ymd"))) {
                                    mkdir("storage/article/".date("Ymd"), 0777, true);
                                }
                                $newwei="storage/article/".date("Ymd").'/'.basename(substr($v, 1));
                                $wo=copy(substr($v, 1), $newwei);
                                if ($wo) {
                                    $data['pic']='/'.$newwei;
                                }
                                break;
                            }
                        }
                    }
                }
            }
            //设置缩率图
            if ($config['thumbnail']==1 and isset($data['pic'])) {
                if (isset($data['pic'])) {
                    $image = \think\Image::open(substr($data['pic'], 1));
                    //计算配置项
                    if (!$config['t_w']) {
                        $config['t_w']=300;
                    }
                    if (!$config['t_h']) {
                        $config['t_h']=$config['t_w'];
                    }
                    $image->thumb($config['t_w'], $config['t_h'])->save(substr($data['pic'], 1));
                }
            }
            //添加水印
            if ($config['watermark']==1) {
                preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr1);
                foreach ($arr1[1] as $k=>$v) {
                    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//') {
                        $image = \think\Image::open(substr($v, 1));
                        $image->text($config['shui_neirong'], dirname(__FILE__).'/FZXBSJW.TTF', $config['shui_zihao'], $config['shui_yanse'], $config['shui_weizhi'], -15)->save(substr($v, 1));
                    }
                }
            }
            if (input('desc')=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags(input('text'))), 0, 200);
            }
            $data['faid']=session('uid');
            if ($o=\app\manage\model\Article::create($data)) {
                $id=$o->id;
                $list = [];
                try {
                    validate(['img_pic'=>'fileSize:5242880|fileExt:jpg,png,gif,webp,jpeg'])->check($file);
                    foreach ($file['img_pic'] as $fi) {
                        $info=\think\facade\Filesystem::disk('public')->putFile( 'article', $fi);
                        $list[]=[
                            'pic'=>'/storage/'.strtr($info, " \ ", " / "),
                            'aid'=>$id
                        ];
                    }
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
                $img= new ArticleImg();
                $img->saveAll($list);
                return '<script>alert("你好，添加成功了！");parent.location.reload()</script>';
            } else {
                $this->error('添加失败了');
            }
        }
        
        $cate=new Catemodel();
        $datasort=$cate->tree();
        foreach ($datasort as $k=>$v) {
            if ($v['type']==2) {
                unset($datasort[$k]);
            }
        }
        View::assign('datasort', $datasort);
        return View::fetch('', [
            'sheng'=>Db::name('area')->where('level_id', 1)->select(),
        ]);
    }
    public function edit()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $validate = new \app\manage\validate\Article;
            if (!$validate->scene('edit')->check($data)) {
                $this->error($validate->getError());
            }
            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            if (input('desc')=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags(input('text'))), 0, 200);
            }
            $file = request()->file('');
            if (isset($file['pic'])) {
                try {
                    validate(['pic'=>'fileSize:5242880|fileExt:jpg,png,gif,webp,jpeg'])->check($file);
                    $info=\think\facade\Filesystem::disk('public')->putFile( 'article', $file['pic']);
                    $data['pic']='/storage/'.strtr($info, " \ ", " / ");
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
            } else {
                if (isset($data['ti'])) {
                    preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
                    foreach ($arr[1] as $k=>$v) {
                        if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
                            $newarr=getimagesize(substr($v, 1));
                            if ($newarr[0] >100 and $newarr[1] >100) {
                                //图片转移位置
                                if (!is_dir("storage/article/".date("Ymd"))) {
                                    mkdir("storage/article/".date("Ymd"));
                                }
                                $newwei="storage/article/".date("Ymd").'/'.basename(substr($v, 1));
                                $wo=copy(substr($v, 1), $newwei);
                                if ($wo) {
                                    $data['pic']='/'.$newwei;
                                }
                                break;
                            }
                        }
                    }
                }
            }
    
            $config=Db::name('config')->column('value', 'key');
            preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
            //压缩图片
            foreach ($arr[1] as $k=>$v) {
                if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//' and is_file(substr($v, 1))) {
                    $newarr=getimagesize(substr($v, 1));
                    if ($config["is_ya"] ==1 and $newarr[0] >$config["ya_w"]) {
                        $image = \think\Image::open(substr($v, 1));
                        $h=$config["ya_w"]*$newarr[1]/$newarr[0];
                        $image->thumb($config['ya_w'], $h)->save(substr($v, 1));
                    }
                }
            }
            
            //设置缩率图
            if ($config['thumbnail']==1 and isset($data['pic'])) {
                $image = \think\Image::open(substr($data['pic'], 1));
                //计算配置项
                if (!$config['t_w']) {
                    $config['t_w']=300;
                }
                if (!$config['t_h']) {
                    $config['t_h']=$config['t_w'];
                }
                $image->thumb($config['t_w'], $config['t_h'])->save(substr($data['pic'], 1));
            }
            //添加水印
            if ($config['watermark']==1) {
                preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr1);
                foreach ($arr1[1] as $k=>$v) {
                    if (substr($v, 0, 4)!='http' and substr($v, 0, 2)!='//') {
                        $image = \think\Image::open(substr($v, 1));
                        $image->text($config['shui_neirong'], dirname(__FILE__).'/FZXBSJW.TTF', $config['shui_zihao'], $config['shui_yanse'], $config['shui_weizhi'], -15)->save(substr($v, 1));
                    }
                }
            }
            $res=Articlemodel::update($data, ['id' => input('id')]);
            if ($res) {
                $list = [];
                    try {
                        validate(['img_pic'=>'fileSize:5242880|fileExt:jpg,png,gif,webp,jpeg'])->check($file);
                        foreach ($file['img_pic'] as $fi) {
                            $info=\think\facade\Filesystem::disk('public')->putFile( 'article', $fi);
                            $list[]=[
                                'pic'=>'/storage/'.strtr($info, " \ ", " / "),
                                'aid'=>input('id')
                            ];
                        }
                    } catch (\think\exception\ValidateException $e) {
                        $this->error($e->getMessage());
                    }
                $img= new ArticleImg();
                $img->saveAll($list);
                $this->success('修改成功', url('article/index', ['st'=>1]));
            } else {
                return $this->error('修改失败了');
            }
        }
        $cid=input('id',0);
        $data=Db::name('article')->where('id', $cid)->find();
        View::assign('data', $data);
        $img=(new ArticleImg())->where('aid', $cid)->select();
        View::assign('img', $img);
        View::assign('type', Db::name('cate')->where('id', $data['cateid'])->value('type'));
        $cate=new Catemodel();
        $datasort=$cate->tree();
        foreach ($datasort as $k=>$v) {
            if ($v['type']==2) {
                unset($datasort[$k]);
            }
        }
        View::assign('datasort', $datasort);
        return View::fetch('', [
            'sheng'=>Db::name('area')->where('level_id', 1)->select(),
            'shi'=>Db::name('area')->where('fid', $data['sheng'])->where('level_id', 2)->select(),
            'xian'=>Db::name('area')->where('fid', $data['shi'])->where('level_id', 3)->select(),
        ]);
    }
}
